
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useLocation, useNavigate,NavLink } from "react-router-dom";
const YAO_CONFIG = {
    6: { name: '老阴', symbol: '--×', isChanging: true },
    7: { name: '少阳', symbol: '—', isChanging: false },
    8: { name: '少阴', symbol: '--', isChanging: false },
    9: { name: '老阳', symbol: '—○', isChanging: true },
  };
  
  const POSITIONS = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻'];

export default function LiuYao() {
  const navigate = useNavigate();
    const [gender, setGender] = useState('男');
    const [divinationTime, setDivinationTime] = useState('');
    const [results, setResults] = useState([]);
    const [isSpinning, setIsSpinning] = useState(false);
    const [remainingSteps, setRemainingSteps] = useState(6);
    const [datatext,setDatatext]=useState({name:''})
    const [result, setResult] = useState('');
    const [error, setError] = useState('');
    

    
    ////
    const  lisTss= (e) => {
      const { name, value } = e.target;
      setDatatext(perv =>({
        ...perv,
        [name]: value
      })
        
      );
    };
    console.log(datatext)
    useEffect(() => {
        const formatTime = () => {
          const now = new Date();
          return `${now.getFullYear()}年${(now.getMonth()+1).toString().padStart(2, '0')}月${now.getDate().toString().padStart(2, '0')}日 ${now.getHours().toString().padStart(2, '0')}时${now.getMinutes().toString().padStart(2, '0')}分`;
        };
        setDivinationTime(formatTime());
      }, []);
    
      // 生成爻象
      const generateYao = () => {
        const coins = Array.from({ length: 3 }, () => (Math.random() > 0.5 ? 2 : 3));
        return YAO_CONFIG[coins.reduce((a, b) => a + b, 0)] || YAO_CONFIG[7];
      };

    
      // 处理摇卦点击
      const handleDivination = () => {
        if (remainingSteps === 0 || isSpinning) return;
    
        setIsSpinning(true);
        setTimeout(() => {
          setResults(prev => [...prev, generateYao()]);
          setRemainingSteps(prev => prev - 1);
          setIsSpinning(false);
        }, 1000);
       
      };
      const tioa= () => {
        // 点击按钮时携带 formData 跳转到子组件路由
        navigate('/zouyi');
      };
  const jiegua = async (datatext) => {


    setLoading(true);
    setError('');
    setResult('');
    try {
      const response = await axios.post('http://localhost:5000/api/askss', formData);
      setResult(response.data.answer);
    } catch (err) {
      setError(err.response?.data?.error || err.response?.data?.details || '请求失败，请稍后重试');
      console.error('API请求错误:', err);
    } finally {
      setLoading(false);
    }

  }

      

      const styles = {
        container: {
          maxWidth: '600px',
          margin: '2rem auto',
          padding: '20px',
          backgroundColor: '#f8f8f8',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        },
        header: {
          display: 'flex',
          justifyContent: 'space-between',
          marginBottom: '20px',
          padding: '10px',
          backgroundColor: '#fff',
          borderRadius: '4px'
        },
        coin: {
          width: '100px',
          height: '100px',
          // backgroundSize: '100% auto',
          // backgroundImage:url('../img/tq.png'),
          borderRadius: '50%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'pointer',
          transition: 'all 0.3s',
          transform: isSpinning ? 'rotate(360deg)' : 'rotate(0deg)',
          animation: isSpinning ? 'spin 1s infinite' : 'none',
 
          
        },
        results: {
          marginTop: '20px',
          display: 'flex',
          flexDirection: 'column-reverse',
          gap: '8px'
        },
        yaoItem: {
          padding: '8px',
          backgroundColor: '#fff',
          borderRadius: '4px',
          display: 'flex',
          justifyContent: 'space-between'
        }
      };
  return (
    <div style={styles.container}>
        
      <div style={styles.header}  >
          {/* <div style={{backgroundImage:'url(../img/tq.png)',}}>

          </div> */}
        <div >起卦时间：{divinationTime}</div>
      </div>

      <div style={{ textAlign: 'center'  }}>
        <div 
          style={styles.coin}
          onClick={handleDivination}
        >
          <div>
            <img src="../img/tq.png" alt="" style={{width:"100px",borderRadius:'50%'}} />
          </div>
           
        </div>
        <div>{isSpinning ? '摇卦中...' : `点击图片开始摇卦 (剩余${remainingSteps}次)`}</div>

        <div style={styles.results}>
          {results.map((yao, index) => (
            <div 
              key={index}
              style={{
                ...styles.yaoItem,
                color: yao.isChanging ? '#c00' : '#333',
                fontWeight: yao.isChanging ? 'bold' : 'normal'
              }}
            >
              <span>{POSITIONS[index]}</span>
              <span>{yao.symbol} {yao.name}</span>
            </div>
          ))}
        </div>
        <div style={{textDecoration:'none'}}><button onClick={tioa}> 开始盘挂</button> </div>
        <div>
        <div className="result-content">
          {/* 保留原有换行格式 */}
          {result.split('\n').map((paragraph, index) => (
            <p key={index}>{paragraph}</p>
          ))}
        </div>
        </div>
      </div>
    </div>
  )
}
